package com.jake.microservice.consumer.controller;

import com.jake.microservice.consumer.constant.UrlConstant;
import com.jake.microservice.model.UserDTO;
import com.jake.microservice.model.UserInfoDTO;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.List;

@RestController
@RequestMapping("users")
public class UserController {

    @Autowired
    private RestTemplate restTemplate;

    @GetMapping
    @HystrixCommand(fallbackMethod = "userFallback")
    public String getUsers() {
        return restTemplate.getForObject(UrlConstant.USERS_URL, String.class);
    }

    @GetMapping("{uid}")
    @HystrixCommand(fallbackMethod = "userFallback")
    public String getUserById(@PathVariable Integer uid) {
        return restTemplate.getForObject(UrlConstant.USERS_URL + uid, String.class);
    }

    @GetMapping("info")
    public List getAllUserInfo() {
        return restTemplate.getForObject(UrlConstant.USERS_URL + "info/", List.class);
    }

    @GetMapping("info/{uid}")
    public UserInfoDTO getUserInfoById(@PathVariable Integer uid) {
        return restTemplate.getForObject(UrlConstant.USERS_URL + "info/" + uid, UserInfoDTO.class);
    }

    @GetMapping("info/{cname}/{username}")
    public List getUserInfoByUsernameAndCname(@PathVariable String username, @PathVariable String cname) {
        return restTemplate.getForObject(UrlConstant.USERS_URL + "info/" + cname + "/" + username, List.class);
    }

    @GetMapping("query")
    @HystrixCommand(fallbackMethod = "userFallback")
    public String getUserEntityByName(String name) {
        return restTemplate.getForObject(UrlConstant.USERS_URL + "query?name=" + name, String.class);
    }

    @PostMapping
    public String addUser(@RequestBody UserDTO user) {
        return restTemplate.postForObject(UrlConstant.USERS_URL, user, String.class);
    }

    @PutMapping("{uid}")
    public void updateUser(@RequestBody UserDTO user, @PathVariable Integer uid) {
        restTemplate.put(UrlConstant.USERS_URL + uid, user);
    }

    @PatchMapping("{uid}")
    public String updateUsername(String username, @PathVariable Integer uid) {
        return restTemplate.patchForObject(UrlConstant.USERS_URL + uid, username, String.class);
    }

    @DeleteMapping("{uid}")
    public void deleteUserById(@PathVariable Integer uid) {
        restTemplate.delete(UrlConstant.USERS_URL + uid);
    }

    public String userFallback() {
        return "您来到了没有用户的荒原";
    }

    public String userFallback(Integer value) {
        return "您来到了没有用户的荒原，输入参数为：" + value;
    }

    public String userFallback(String value) {
        return "您来到了没有用户的荒原，输入参数为：" + value;
    }

}
